#!/bin/env bash
# 实例文件
# 用于asciidoc的O'Reilly图书工具包装器

# 普通的完备性检查
[ -n "$BOOK_ASC" ] || {
    echo "FATAL: must export \$BOOK_ASC to the location of '...bcb2/head/asciidoc/'!"
    exit 1
}

\cd  "$BOOK_ASC" || {
    echo "FATAL: can't cd to '$BOOK_ASC'!"
    exit 2
}

SELF="$0"

action="$1"
shift

[ -x /usr/bin/xsel -a $# -lt 1 ] && {
    text=$(xsel -b)
    function Output {
        echo -en "$*" | xsel -bi
    }
} || {
    text=$*
    function Output {
        echo -en "$*"
    }
}


case "$action" in
    rec|recipe )
        id="$($SELF id $text)"
        Output "$(cat <<- EoF
            [[$id]]
            === $text
            
            [[problem-$id]]
            ==== Problem
            
            [[solution-$id]]
            ==== Solution
            
            [[discussion-$id]]
            ==== Discussion
            
            [[see_also-$id]]
            ==== See Also
            * \`man \`
            * item1
            * <<xref-id-here>>
            * URL[text]
            EoF 
        )" 
    ;;

    table )
        Output "$(cat <<- EoF
            .A Table
            [options="header"]
            |=======
            |head|h|h
            |cell|c|c
            |cell|c|c
            |=======
            EoF
        )"
    ;;

    h1 )
        Output "=== $text"
    ;;
    h2 )
        Output "==== $text"
    ;;
    h3 )
        Output "===== $text"
    ;;
    bul|bullet )
        Output ". $text"
    ;;
    nul|number|order* )
        Output "# $text"
    ;;
    term )
        Out "term_here::\n $text"
    ;;
    cleanup )
        rm -fv {ch??,app?}.{pdf,xml,html} book.xml docbook-xsl.css
    ;;

    * )
        \cd - > /dev/null
        ( echo "Usage:"
        egrep '\)[[:space:]]+# '    $SELF
        echo ''
        egrep '\)[[:space:]]+## '   $SELF) | more
    ;;
esac
